import React from 'react';
import {
  Table, Divider, Button, message, Popconfirm
} from 'antd';
import { connect } from 'dva';
import AddSysModal from '@/components/AddSysModal';

let groupMap = new Map();

class SysList extends React.Component {

  state={
    modalVisible: false,
    currentSys: undefined,
  }

  onUpdateSys = (record) => {
    this.setState({
      modalVisible: !this.state.modalVisible,
      currentSys: record,
    });
  }

  handleModalVisible = () => {
    this.setState({
      modalVisible: !this.state.modalVisible,
      currentSys: undefined,
    })
  }

  updateSys = (payload) => {
    const { dispatch, global: {env} } = this.props;
    let type="sys/updateSys";
    if(!payload.id){ //修改
      type="sys/addSys";
      Object.assign(payload, {
        mode: env,  //环境 0-uat 1-bbj 2-准生产
      });
    }
    dispatch({
      type,
      payload,
    }).then(res => {
      if(res){
        message.success("修改成功");
        this.setState({
          currentSys: undefined,
          modalVisible: false,
        });
      }
    });
  }

  onDeleteSys = (id) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'sys/delSys',
      payload: {
        id,
      }
    }).then(res => {
      if(res){
        message.success("删除成功!");
      }
    });
  }

  render(){

    const { global: {group}, sys: {sysList} } = this.props;

    group.forEach(item => {
      groupMap.set(item.id, item.name);
    });

    const newSysList = sysList.map(item => ({
      ...item,
      groupName: groupMap.get(item.sysgroup),
    }));

    const columns = [{
      title: '应用名称',
      dataIndex: 'name'
    },
    {
      title: '所属系统',
      dataIndex: 'groupName'
    },
    {
      title: '操作',
      render: (text, record) => {
        return (
          <span>
            <a onClick={() => this.onUpdateSys(record)}>修改</a>
            <Divider type="vertical" />
            <Popconfirm title="确认删除？" onConfirm={() => this.onDeleteSys(record.id)}>
              <a>删除</a>
            </Popconfirm>
          </span>
        );
      }
    }];

    const { modalVisible, currentSys } = this.state;

    return (
      <div>
        <Button type="primary" icon="plus" style={{marginBottom: 20}}
          onClick={this.handleModalVisible}>新增</Button>
        <Table columns={columns} dataSource={newSysList} bordered={true} rowKey="id" />
        { modalVisible ? <AddSysModal
          value={currentSys}
          modalVisible={modalVisible}
          okHandle={this.updateSys}
          group={group}
          handleModalVisible={this.handleModalVisible}/> : null }
      </div>
    );
  }
}

export default connect(({global, sys}) => ({
  global,
  sys,
}))(SysList);
